package com.hcb.utils;

import com.google.gson.Gson;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/websocket/{userName}")
public class Websocket {

    private static Map<String,Session> sessionPool = new HashMap<String,Session>();
    @OnOpen
    public void onOpen(Session session, @PathParam(value="userName")String userName) {
        System.out.println(userName + "open");
        sessionPool.put(userName, session);
    }

    @OnClose
    public void onClose( @PathParam(value="userName")String userName) {
        sessionPool.remove(userName);
        System.out.println(userName+"close");
    }

    @OnMessage
    public void onMessage(@PathParam(value="userName")String userName,String message) {
        System.out.println("【websocket消息】收到客户端消息:"+message);
    }


    // 此为单点消息-单用户通知
    public static  void  sendOneMessage(String userName, Map message) {
        Session session = sessionPool.get(userName);
        if (session != null) {
            System.out.println("【websocket消息】单点消息:"+message);
            try {
                session.getAsyncRemote().sendText(new Gson().toJson(message));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
